/**
 * 智慧小区管理系统 - 路由生成器
 * 
 * 权限控制粒度简化：
 * - 根据菜单权限生成动态路由
 * - 简化路由权限验证逻辑
 * 
 * @author Wu.Liang
 * @date 2024-01-01
 * @updated 2025-07-02 - 权限控制粒度简化
 */
import type { RouteRecordRaw } from 'vue-router'
import { usePermissionStore } from '@/store/permission'
import { useUserStore } from '@/store/user'
import { ROLE_CODES } from '@/constants/roles'

// 路由配置接口
export interface RouteConfig {
    path: string
    name: string
    component?: string
    redirect?: string
    meta: {
        title: string
        icon?: string
        permission?: string
        requiresAuth?: boolean
        hidden?: boolean
    }
    children?: RouteConfig[]
}

/**
 * 根据菜单权限生成动态路由
 * @param menuPermissions 菜单权限列表
 * @returns 动态路由列表
 */
export function generateRoutes(menuPermissions: string[]): RouteRecordRaw[] {
    const userStore = useUserStore()
    const permissionStore = usePermissionStore()

    // 超级管理员拥有所有路由
    if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
        return generateAllRoutes()
    }

    // 根据用户菜单权限过滤路由
    const filteredRoutes = filterRoutesByPermissions(generateAllRoutes(), menuPermissions)
    
    return filteredRoutes
}

/**
 * 生成所有路由配置
 * @returns 所有路由配置
 */
function generateAllRoutes(): RouteRecordRaw[] {
    return [
        {
            path: '/user',
            name: 'User',
            redirect: '/user/list',
            meta: { title: '用户管理', icon: 'User', requiresAuth: true },
            children: [
                {
                    path: 'list',
                    name: 'UserList',
                    component: () => import('@/views/user/UserList.vue'),
                    meta: { title: '用户列表', permission: 'user:menu' }
                },
                {
                    path: 'role',
                    name: 'RoleList',
                    component: () => import('@/views/user/RoleList.vue'),
                    meta: { title: '角色管理', permission: 'role:menu' }
                },
                {
                    path: 'permission',
                    name: 'PermissionList',
                    component: () => import('@/views/user/PermissionList.vue'),
                    meta: { title: '权限管理', permission: 'permission:menu' }
                }
            ]
        },
        {
            path: '/region',
            name: 'Region',
            redirect: '/region/list',
            meta: { title: '区域管理', icon: 'Location', requiresAuth: true },
            children: [
                {
                    path: 'list',
                    name: 'RegionList',
                    component: () => import('@/views/region/RegionList.vue'),
                    meta: { title: '区域列表', permission: 'region:menu' }
                }
            ]
        },
        {
            path: '/property',
            name: 'Property',
            redirect: '/property/company',
            meta: { title: '物业管理', icon: 'OfficeBuilding', requiresAuth: true },
            children: [
                {
                    path: 'company',
                    name: 'PropertyCompany',
                    component: () => import('@/views/property/company/PropertyCompanyList.vue'),
                    meta: { title: '物业公司' }
                },
                {
                    path: 'info',
                    name: 'PropertyInfo',
                    component: () => import('@/views/property/PropertyInfo.vue'),
                    meta: { title: '物业信息' }
                }
            ]
        }
    ]
}

/**
 * 根据权限过滤路由
 * @param routes 路由列表
 * @param menuPermissions 菜单权限列表
 * @returns 过滤后的路由列表
 */
function filterRoutesByPermissions(routes: RouteRecordRaw[], menuPermissions: string[]): RouteRecordRaw[] {
    return routes.filter(route => {
        // 检查路由是否有权限要求
        const requiredPermission = route.meta?.permission as string
        if (!requiredPermission) {
            return true
        }

        // 检查用户是否有该菜单权限
        const hasPermission = menuPermissions.includes(requiredPermission)
        
        if (!hasPermission) {
            console.log(`路由权限检查失败: ${route.path} - 缺少权限: ${requiredPermission}`)
            return false
        }

        // 递归处理子路由
        if (route.children && route.children.length > 0) {
            route.children = filterRoutesByPermissions(route.children, menuPermissions)
            
            // 如果子路由全部被过滤掉，则隐藏父路由
            if (route.children.length === 0) {
                return false
            }
        }

        return true
    })
}

/**
 * 验证路由权限
 * @param route 路由对象
 * @param menuPermissions 菜单权限列表
 * @returns 是否有权限访问
 */
export function validateRoutePermission(route: RouteRecordRaw, menuPermissions: string[]): boolean {
    const userStore = useUserStore()

    // 超级管理员拥有所有权限
    if (userStore.userRoles.includes(ROLE_CODES.SUPER_ADMIN)) {
        return true
    }

    // 检查路由是否有权限要求
    const requiredPermission = route.meta?.permission as string
    if (!requiredPermission) {
        return true
    }

    // 检查用户是否有该菜单权限
    return menuPermissions.includes(requiredPermission)
}

/**
 * 获取用户可访问的路由
 * @returns 可访问的路由列表
 */
export function getAccessibleRoutes(): RouteRecordRaw[] {
    const permissionStore = usePermissionStore()
    const menuPermissions = permissionStore.menuPermissionCodes
    
    return generateRoutes(menuPermissions)
}

/**
 * 检查路由是否需要认证
 * @param route 路由对象
 * @returns 是否需要认证
 */
export function isRouteRequiresAuth(route: RouteRecordRaw): boolean {
    return route.meta?.requiresAuth === true
}

/**
 * 获取路由标题
 * @param route 路由对象
 * @returns 路由标题
 */
export function getRouteTitle(route: RouteRecordRaw): string {
    return route.meta?.title as string || '未知页面'
}

/**
 * 获取路由图标
 * @param route 路由对象
 * @returns 路由图标
 */
export function getRouteIcon(route: RouteRecordRaw): string | undefined {
    return route.meta?.icon as string
}

/**
 * 检查路由是否隐藏
 * @param route 路由对象
 * @returns 是否隐藏
 */
export function isRouteHidden(route: RouteRecordRaw): boolean {
    return route.meta?.hidden === true
} 